use std::ops::Add;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::Receiver;
use std::thread;
use std::thread::{Builder, sleep};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::threadpool::task::Task;

/// is_core:  ture, 核心线程，不能销毁； false， 非核心线程，可以销毁
/// name:   "Core_Worker_i", 核心线程，i 是整形标记； “Help_Worker_i”, 非核心线程，i 是整形标记
/// worker  ,std::thread::Builder
#[derive(Debug)]
pub struct Worker {
    name                :   String,
    worker              :   Builder,
    active_time         :   usize,//线程存活时间, 单位秒
    is_core             :   bool,
    is_working          :   bool,
}

impl Worker {
    pub fn new(id: usize, active_time:usize, is_core: bool) ->Self {
        let builder = thread::Builder::new();
        let name = if is_core {
            "Core_Worker_".to_owned().add(&*id.to_string())
        }else {
            "Help_Worker_".to_owned().add(&*id.to_string())
        };
        Worker{
            name,
            active_time,
            worker      :   builder,
            is_core,
            is_working: false,
        }
    }

    pub fn is_working(&self) -> &bool{
        &self.is_working
    }

    pub fn name(&self) -> &str{
        &self.name
    }


    pub fn work(&mut self, receiver: Arc<Mutex<Receiver<Task>>>){
        let start_working = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let is_core = self.is_core.clone();
        let active_time = self.active_time.clone();
        let name = self.name.clone();

        let is_working = Arc::new(Mutex::new(self.is_working));// 必须使用Mutex

        let is_working_arc = Arc::clone(&is_working);

        thread::spawn(move || loop{
            sleep(Duration::new(10,0));
            if is_core {
                println!("{} thread starts to work", name);
                let job = receiver.lock().unwrap().recv().unwrap();
                let mut is_working_arc = is_working_arc.lock().unwrap();
                *is_working_arc = true;
                job.task(name.clone())();
                *is_working_arc = false;
            } else {
                let current_time = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs();
                if current_time-start_working> active_time as u64 {
                    break;
                }else {
                    println!("{} thread is woring...", name);
                    let job = receiver.lock().unwrap().recv().unwrap();
                    let mut is_working_arc = is_working_arc.lock().unwrap();
                    *is_working_arc = true;
                    job.task(name.clone())();
                    *is_working_arc = false;
                }
            }
        });



    }
}